package com.ki.rent.service.impl;

import com.aliyun.oss.OSSClient;
import com.ki.rent.service.UploadService;
import com.ki.util.DateUtils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *
 */
@Service
public class UploadServiceImpl implements UploadService {


    @Value("${rent.file.oss-endpoint}")
    private String endpoint;
    @Value("${rent.file.oss-accessKeyId}")
    private String accessKeyId;
    @Value("${rent.file.oss-accessKeySecret}")
    private String accessKeySecret;
    @Value("${rent.file.oss-bucketName}")
    private String bucketName;

    @Override
    public Map<String, Object> uploadFile(MultipartFile file) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = null;
        //前端裁剪后文件没有后缀名
        if (fileName.indexOf(".") > -1) {
            suffixName = "." + FilenameUtils.getExtension(fileName).toLowerCase();
        } else {
            suffixName = ".png";
        }
        String newfileName = uuid + suffixName;  // 文件名
        if (suffixName.contains("jpg") || suffixName.contains("png")
                || suffixName.contains("JPG") || suffixName.contains("PNG")
                || suffixName.contains("jpeg") || suffixName.contains("JPEG")
                || suffixName.contains("zip") || suffixName.contains("rar")
                || suffixName.contains("pdf") || suffixName.contains("ZIP")
                || suffixName.contains("RAR") || suffixName.contains("PDF")) {
            String folder = "dev/" + DateUtils.getyyyyMM();
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, folder + "/" + newfileName, file.getInputStream());
            // 设置URL过期时间为1小时。
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(bucketName, newfileName, expiration);
            ossClient.shutdown();
            map.put("image", "http://" + bucketName + "." + endpoint.substring(7, endpoint.length()) + "/" + folder + "/" + newfileName);
        }
        map.put("code", 0);
        map.put("msg", "上传成功");
        return map;
    }
}
